package mate.task.odin;

import java.io.FileOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;

/**
 * This class represents a database of UserAccount objects
 * @author Leonard
 * @version 1.0
 */
public class UserDatabase implements Serializable{
	
	private HashMap<String,UserAccount> users;
	private static UserDatabase db;
	private UserAccount currentUser;
	static ArrayList<UserAccount> userList;
	/**
	 * Creates a new UserDatabase object. If past data exists, loads that in. Otherwise, creates
	 * new HashMap.
	 */
	private UserDatabase(){
		//try to get past data from database here, or new hashmap if no data
		users = new HashMap<String,UserAccount>();
		addUser("default", "default", "default", "default");
	}
	
	/**
	 * Adds a new user with specified data to the user database. If the username already
	 * exists, null is returned.
	 * @param name The new user's full name
	 * @param email The new user's email
	 * @param username The new user's username
	 * @param password The new user's password
	 * @return The new UserAccount object is adding is successful, or null if same username exists
	 */
	public UserAccount addUser(String name, String email, String username, String password){
		UserAccount newUser = null;
		
		if(!users.containsKey(username)){
			newUser = new UserAccount(name,email,username,password);
			users.put(username,newUser);
		}
		
		currentUser = newUser;
		userList.add(newUser);
		return newUser;
	}
	
	/**
	 * Attempts to log an existing user in. Returns null if login fails or the user account if
	 * successful.
	 * @param name The user's username 
	 * @param password The user's password
	 * @return The UserAccount object if login succeeds, null if login fails.
	 */
	public UserAccount login(String name, String password){
		UserAccount user = users.get(name);
		
		if(user != null){
			
			String tempPass = user.getPassword();
			
			//username exists, but password is incorrect
			if(!tempPass.equals(password))
				user = null;
		}
		currentUser = user;
		return user;
	}
	
	/**
	 * Returns the currently logged in user
	 * @return The currently logged in user
	 */
	public UserAccount getCurrentUser(){
		return currentUser;
	}
	
	/**
	 * Returns the singleton instance of UserDatabase
	 * @return The singleton instance of UserDatabase
	 */
	public static UserDatabase getDatabaseInstance(){
		if(db == null)
		{
			userList = new ArrayList<UserAccount>();
			db = new UserDatabase();
		}
		return db;
	}
	
	/**
	 * Prompts the UserDatabase to save all UserAccount information (as well as their ToDo data).
	 */
	public ArrayList<UserAccount> getUsers(){
		return userList;
	}
}
